<template>
  <div class="roles-container">
    <!-- 面包屑导航start -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航end -->

    <!-- 卡片视图start -->
    <el-card>
      <el-button type="primary" @click="addRolesDialogFormVisible = true"
        >添加角色</el-button
      >
      <!-- 角色列表 -->
      <el-table :data="rolesList" border>
        <!-- 下拉菜单 -->
        <el-table-column type="expand" width="60">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', index1 === 0 ? 'bdtop' : '']"
            >
              <!-- 一级权限 -->
              <el-col :span="4">
                <el-tag closable @close="removeRight(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二,三级权限 -->
              <el-col :span="20">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 === 0 ? '' : 'bdtop']"
                >
                  <!-- 二级权限 -->
                  <el-col :span="5">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRight(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="19">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      style="margin-right: 10px"
                      closable
                      @close="removeRight(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" width="70" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button-group>
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                @click="
                  editRolesDialogFormVisible = true
                  showEditRolesInfo(scope.row.id)
                "
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="delRoles(scope.row)"
              ></el-button>
              <el-tooltip
                effect="dark"
                content="分配权限"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="success"
                  icon="el-icon-setting"
                  size="mini"
                  @click="setRights()"
                ></el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 卡片视图end -->
    <!-- 分配角色权限对话框 start-->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="500px"
    >
      <!-- 权限列表 -->
      <el-tree :data="rightsList" :props="rightProps" show-checkbox default-expand-all> </el-tree>
      <span slot="footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRightsDialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 分配角色权限对话框end -->

    <!-- 新增角色对话框start -->
    <el-dialog
      title="新增角色"
      :visible.sync="addRolesDialogFormVisible"
      width="500px"
      @close="resetAddRolesForm"
    >
      <el-form
        :model="addRolesForm"
        :rules="rolesFormRules"
        ref="addRolesFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogFormVisible = false">取 消</el-button>
        <el-button type="warning" @click="resetAddRolesForm">重置</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增角色对话框end -->

    <!-- 修改角色对话框start -->
    <el-dialog
      title="修改角色"
      :visible.sync="editRolesDialogFormVisible"
      width="500px"
    >
      <el-form
        :model="editRolesInfo"
        :rules="rolesFormRules"
        ref="editRolesFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="editRolesInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editRolesDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改角色对话框end -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 控制分配权限对话框的显示与隐藏
      setRightsDialogVisible: false,
      // 角色权限列表
      rightsList: [],
      // 控制新增角色对话框的显示与隐藏
      addRolesDialogFormVisible: false,
      // 新增角色表单数据
      addRolesForm: {
        roleName: '',
        roleDesc: '',
      },
      // 新增角色表验证规则
      rolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '角色名长度在2到10之前',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          { required: true, message: '请输入该角色的描述', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '角色描述长度在2到10之间',
            trigger: 'blur',
          },
        ],
      },
      // 要修改的角色信息
      editRolesInfo: {},
      // 控制修改角色对话框的显示与隐藏
      editRolesDialogFormVisible: false,
      rightProps: {
        children: 'children',
        label: 'authName'
      }
    }
  },
  methods: {
    // 获取角色
    async getRolesList() {
      const { data } = await this.$http.get('roles')
      // console.log(data)
      // 判断是否获取成功
      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      // 获取成功添加到角色列表中
      this.rolesList = data.data
      // console.log(this.rolesList)
    },
    // 获取所有权限
    async getRightsList() {
      // 获取权限
      const { data } = await this.$http.get('rights/tree')
      // 判断是否获取成功
      if (data.meta.status !== 200) {
        return this.$message.error(data.meta.msg)
      }
      this.rightsList = data.data
      console.log(this.rightsList)
    },
    // 分配权限
    async setRights() {
      // 打开分配权限对话框
      this.setRightsDialogVisible = true
      // 获取所有权限
      const { data } = await this.$http.get('rights/tree')
      // 判断权限是否获取成功
      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      // 将获取到的数据绑定到data的rights中
      this.rightsList = data.data
      console.log(this.rightsList)
    },
    // 移除权限 role：当前行的信息，rightId：要移除的权限id
    removeRight(role, rightId) {
      this.$confirm('是否移除该权限', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 执行删除
          const { data } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          )
          // 判断是否删除成功
          if (data.meta.status !== 200) {
            return this.$message.error(data.meta.msg)
          }
          this.$message.success('移除成功')
          // 重新获取拥有的权限
          role.children = data.data
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 添加角色
    async addRoles() {
      // 传递当前添加角色表的信息执行添加
      const { data } = await this.$http.post('roles', this.addRolesForm)
      console.log(data)
      // 判断是否添加成功
      if (data.meta.status !== 201) {
        return this.$message.error(data.meta.msg)
      }
      this.$message.success(data.meta.msg)
      // 成功后关闭对话框
      this.addRolesDialogFormVisible = false
      // 刷新角色表
      this.getRolesList()
    },
    // 根据id查询要修改的当前角色信息
    async showEditRolesInfo(rolesId) {
      const { data } = await this.$http.get('roles/' + rolesId)
      if (data.meta.status !== 200) {
        return this.$message.error(data.meta.msg)
      }
      this.editRolesInfo = data.data
      console.log(this.editRolesInfo)
    },
    // 修改角色
    async editRoles() {
      // put执行修改
      const { data } = await this.$http.put('roles/' + this.editRolesInfo.roleId, this.editRolesInfo)
      // console.log(data)
      // 判断是否修改成功
      if(data.meta.status !== 200) {
        return this.$message.error(data.meta.msg)
      }
      this.$message.success('修改成功')
      // 修改成功后关闭对话框
      this.editRolesDialogFormVisible = false
      // 重新获取角色列表
      this.getRolesList()
    },
    // 重置添加角色表
    resetAddRolesForm() {
      this.$refs.addRolesFormRef.resetFields()
    },
    // 删除角色
    delRoles(userInfo) {
      console.log(userInfo)
      this.$confirm(`是否删除姓名为${userInfo.roleName}的角色`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          // 执行删除
          const { data } = await this.$http.delete('roles/' + userInfo.id)
          console.log(data)
          // 判断是否删除成功，并提示删除的信息
          if (data.meta.status !== 200) {
            return this.$message.error(data.meta.msg)
          }
          this.$message.success(data.meta.msg)
          // 重新获取角色列表
          this.getRolesList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
  // 页面加载时执行
  created() {
    // 获取所有角色
    this.getRolesList()
  },
}
</script>

<style lang="less" scoped>
.roles-container {
  height: 100%;
  overflow-x: hidden;
  padding: 10px;
  .el-button:nth-of-type(1) {
    margin-bottom: 15px;
  }
  .el-table {
    /* 设置一级权限上下居中 */
    .el-row:nth-of-type(1) {
      display: flex;
      align-items: center;
    }
    .el-row {
      padding: 10px 0;
      .el-col {
        /* 清除二级权限第一个的顶部内间距 */
        .el-row:nth-of-type(1) {
          padding-top: 0;
        }
      }
    }
    .el-button-group {
      .el-button {
        margin-right: 10px;
      }
    }
  }

  .bdtop {
    border-top: 1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
}
</style>
